package com.it.day7;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * ClassName: AtomicReferenceFieldUpdaterDemo
 * Description: 对象的引用类型属性修改原子类
 *
 * @Author: csx
 * @Create: 2025/5/13 - 17:24
 * @version: v1.0
 */
public class AtomicReferenceFieldUpdaterDemo {
    public static void main(String[] args) {
        MyVar myVar = new MyVar();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myVar.init();
            }, String.valueOf(i)).start();
        }
    }
}

class MyVar{
    private volatile Boolean isInit = Boolean.FALSE;
    AtomicReferenceFieldUpdater<MyVar,Boolean> fieldUpdater =
            AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");

    public void init(){
        if (fieldUpdater.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) {
            System.out.println(Thread.currentThread().getName()+"\t---init.....");

            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

            System.out.println(Thread.currentThread().getName()+"\t---init.....over");
        } else {
            System.out.println(Thread.currentThread().getName()+"\t------其它线程正在阻塞");
        }
    }
}
















